package com.anxin.act.model.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.busFlow.entity.WfBusNode;
import com.anxin.act.busFlow.service.WfBusNodeService;
import com.anxin.act.config.dao.WfApplyFormFieldDao;
import com.anxin.act.config.entity.WfApplyFormField;
import com.anxin.act.model.dao.WfActApproverDao;
import com.anxin.act.model.entity.WfActApprover;
import com.anxin.act.utils.ActModelUtils;
import com.anxin.act.utils.ActProcessUtils;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.IdGen;
import com.anxin.common.utils.JsonUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sign.Base64;
import com.anxin.common.utils.sys.DeptUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.web.entity.AjaxResult;
import com.anxin.framework.web.service.BaseService;
import com.anxin.sys.sql.dao.SqlDao;
import com.anxin.sys.system.dao.SysDeptDao;
import com.anxin.sys.system.dao.SysRoleDao;
import com.anxin.sys.system.dao.SysUserDao;
import com.anxin.sys.system.entity.SysDept;
import com.anxin.sys.system.entity.SysRole;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.VariableInstance;
import org.activiti.engine.repository.Model;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.poi.hpbf.model.qcbits.QCBit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流审批人配置Service业务层处理
 *
 * @author jbs
 * @date 2020-03-18
 */
@Service
public class WfActApproverService extends BaseService<WfActApproverDao, WfActApprover>{
    @Autowired
    private WfActApproverDao wfActApproverDao;

    @Autowired
    private SysDeptDao sysDeptDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private WfApplyFormFieldDao wfApplyFormFieldDao;

    @Autowired
    private SqlDao sqlDao;

    @Autowired
    private WfBusNodeService wfBusNodeService;

    @Autowired
    private RuntimeService runtimeService;


    /**
     * 获取部门待选数据
     * @return
     */
    public List<Map<String,Object>> getDeptData(){
        List<SysDept> sysDeptList = sysDeptDao.selectDeptList(new SysDept());
        List<Map<String,Object>> resList = new ArrayList<>();
        for (SysDept sysDept : sysDeptList) {
            Map<String,Object> deptMap = new HashMap<>();
            deptMap.put("id",sysDept.getId());
            deptMap.put("pId",sysDept.getParentId());
            deptMap.put("key",sysDept.getDeptKey());
            deptMap.put("name",sysDept.getDeptName());
            deptMap.put("open","true");
            resList.add(deptMap);
        }
        return resList;
    }


    /**
     * 获取部门和用户的树形结构数据
     * @return
     */
    public List<Map<String,Object>> getUserData(){
        List<Map<String, Object>> resList = this.getDeptData();

        //前台zTree选择时会过去ID已temp_开头的
        for (Map<String, Object> deptMap : resList) {
            deptMap.put("id","temp_"+deptMap.get("id"));
            deptMap.put("pId","0".equals(deptMap.get("pId"))?"0":"temp_"+deptMap.get("pId"));
            deptMap.put("type","dept");
        }

        List<SysUser> sysUserList = sysUserDao.selectUserList(new SysUser());

        for (SysUser sysUser : sysUserList) {
            Map<String,Object> deptMap = new HashMap<>();
            deptMap.put("id",sysUser.getId());
            deptMap.put("pId","temp_"+sysUser.getDeptId());
            deptMap.put("key",sysUser.getUserName());
            deptMap.put("name",sysUser.getNickName());
            deptMap.put("type","user");
            resList.add(deptMap);
        }
        return resList;
    }

    /**
     * 获取角色树形结数据
     * @return
     */
    public List<Map<String,Object>> getRoleData(){
        List<Map<String,Object>> resList = new ArrayList<>();

        List<SysRole> sysRoleList = sysRoleDao.selectRoleList(new SysRole());

        for (SysRole sysRole : sysRoleList) {
            Map<String,Object> roleMap = new HashMap<>();
            roleMap.put("id",sysRole.getRoleId());
            roleMap.put("pId","0");
            roleMap.put("name",sysRole.getRoleName());
            roleMap.put("key",sysRole.getRoleKey());
            resList.add(roleMap);
        }

        return resList;

    }

    /**
     * 获取表单属性字段
     * @param modelId
     * @return
     */
    public List<Map<String,Object>> getFormFieldData(String modelId){
        List<Map<String,Object>> resFieldList = new ArrayList<>();

        Model model = repositoryService.getModel(modelId);
        JSONObject metaInfo = JSONObject.parseObject(model.getMetaInfo());
        String formType = metaInfo.getString("formType");
        String formId = metaInfo.getString("formId");

        if ("dev".equals(formType)){
            List<WfApplyFormField> wfApplyFormFieldList = wfApplyFormFieldDao.getByApplyFormId(formId);
            for (WfApplyFormField wfApplyFormField : wfApplyFormFieldList) {
                if ("User".equals(wfApplyFormField.getType()) || "Office".equals(wfApplyFormField.getType())  ){
                    Map<String,Object> fieldMap = new HashMap<>();
                    fieldMap.put("id",wfApplyFormField.getId());
                    fieldMap.put("key",wfApplyFormField.getName());
                    fieldMap.put("name",wfApplyFormField.getRemark());
                    resFieldList.add(fieldMap);
                }

            }
        }

        return resFieldList;
    }



    /**
     * 保存数据
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    public AjaxResult save(String data){
        JSONObject dataJson = JSONObject.parseObject(Base64.decodeBase64String(data));
        String actUuid = dataJson.getString("actUuid");
        String modelId = dataJson.getString("modelId");

        String configType = dataJson.getString("configType");

        // 删除之前配置的数据
        wfActApproverDao.deleteByActUuid(actUuid);

        // 用户数据
        JSONArray userArray = dataJson.getJSONArray("userKeyList");
        for (int i = 0; i < userArray.size(); i++) {
            String userKey = userArray.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"user",userKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 部门数据
        JSONArray deptArray = dataJson.getJSONArray("deptKeyList");
        for (int i = 0; i < deptArray.size(); i++) {
            String deptKey = deptArray.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"dept",deptKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 角色数据
        JSONArray roleArray = dataJson.getJSONArray("roleKeyList");
        for (int i = 0; i < roleArray.size(); i++) {
            String roleKey = roleArray.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"role",roleKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 表单数字
        JSONArray formFieldKeyArray = dataJson.getJSONArray("formFieldKeyList");
        for (int i = 0; i < formFieldKeyArray.size(); i++) {
            String formFieldKey = formFieldKeyArray.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"form_field",formFieldKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 相对角色
        JSONArray relativeArray = dataJson.getJSONArray("relativeList");
        for (int i = 0; i < relativeArray.size(); i++) {
            String relativeKey = relativeArray.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"relative",relativeKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 项目团队成员
        JSONArray dealTeamKeyList = dataJson.getJSONArray("dealTeamKeyList");
        for (int i = 0; i < dealTeamKeyList.size(); i++) {
            String dealTeamKey = dealTeamKeyList.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"deal_team",dealTeamKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        // 基金团队成员
        JSONArray fundTeamKeyList = dataJson.getJSONArray("fundTeamKeyList");
        for (int i = 0; i < fundTeamKeyList.size(); i++) {
            String fundTeamKey = fundTeamKeyList.getString(i);
            WfActApprover wfActApprover = new WfActApprover(actUuid,modelId,"fund_team",fundTeamKey,configType);
            wfActApproverDao.insert(wfActApprover);
        }

        return AjaxResult.success();
    }

    /**
     * 根据actUuid,modelId 查询数据
     * @param actUuid
     * @return
     */
    public List<WfActApprover> findList(String actUuid){
        WfActApprover wfActApprover = new WfActApprover();
        wfActApprover.setActUuid(actUuid);
        return wfActApproverDao.findList(wfActApprover);
    }

    @Transactional(readOnly = false)
    public String copyByUuid(String oldUuid){
        String newUuid = IdGen.uuid();
        List<WfActApprover> actApproverList = this.findList(oldUuid);
        for (WfActApprover wfActApprover : actApproverList) {
            wfActApprover.setId(null);
            wfActApprover.setActUuid(newUuid);
            this.save(wfActApprover);
        }
        return newUuid;
    }


    /**
     * 获取流程审批人
     * @param actUuid
     * @param modelId
     * @param processInstance
     * @param processVar
     * @return
     */
    public List<String> getApprover(String actUuid, String modelId, ProcessInstance processInstance,Map<String,Object> processVar,String activityId){
        List<String> resList = new ArrayList<String>();
        List<WfActApprover> approverList = this.findList(actUuid);

        // 是否是抄送
        boolean isCc = false;

        for (WfActApprover wfActApprover : approverList) {
            String type = wfActApprover.getType();
            if ("ccUsers".equals(wfActApprover.getConfigType())){
                isCc = true;
            }

            switch (type){
                case "user":this.getApproverByUser(wfActApprover,resList);break;
                case "dept":this.getApproverByDept(wfActApprover,resList);break;
                case "role":this.getApproverByRole(wfActApprover,resList);break;
                case "relative":this.getApproverByRelative(wfActApprover,resList,processInstance,processVar);break;
                case "fund_team":this.getApproverByFundTeam(wfActApprover,resList,processInstance,processVar);break;
                case "deal_team":this.getApproverByDealTeam(wfActApprover,resList,processInstance,processVar);break;
                case "form_field":this.getApproverByFormField(wfActApprover,resList,processInstance,processVar);
            }
        }

        // 如果是抄送则不从流程变量中取获取审批人
        if (!isCc && processInstance != null && StringUtils.isNotBlank(processInstance.getId())){
            // 根据流程变量设置审批人
            this.getApproverByVar(processInstance,resList,processVar,activityId);
        }


        return resList;
    }

    /**
     * 获取业务表和业务ID
     * @param processInstance
     * @param processVar
     * @return
     */
    public Map<String,String> getDataTableAndDataId(ProcessInstance processInstance,Map<String,Object> processVar){
        Map<String, String> dataTableAndDataId = new HashMap<>();
        if (processVar != null){
            dataTableAndDataId.put("actDataId",processVar.get("actDataId").toString());
            dataTableAndDataId.put("actDataTable",processVar.get("actDataTable").toString());
        }else {
            dataTableAndDataId.put("actDataId",((ExecutionEntity) processInstance).getVariable("actDataId").toString());
            dataTableAndDataId.put("actDataTable",((ExecutionEntity) processInstance).getVariable("actDataTable").toString());
        }

        return dataTableAndDataId;
    }


    /**
     * 获取流程审批人
     * @param actUuid
     * @param modelId
     * @return
     */
    public List<String> getApprover(String actUuid, String modelId, ProcessInstance processInstance,String activityId){
        Map<String,Object> processVar = null;
        Map<String, Object> processVariables = processInstance.getProcessVariables();
        if (processVariables != null && processVariables.keySet().size() > 0){
            processVar = processVariables;
        }
        return this.getApprover(actUuid,modelId,processInstance,processVar,activityId);

    }

    /**
     * 根据流程变量获取审批人
     * @param processInstance 流程实例
     */
    public void getApproverByVar(ProcessInstance processInstance,List<String> resList,Map<String,Object> processVar,String activityId){
        if(processInstance != null || processVar != null){

            String variableKey = "nodeApprover_" + activityId;

            if (processVar == null){
                processVar  = ActUtils.getProcessVar(processInstance.getProcessInstanceId());
            }

            JSONArray approverArray = null;
            if (processVar.get("actNextNodeApprover") != null && !"".equals(processVar.get("actNextNodeApprover").toString())){
                approverArray = JSONArray.parseArray(processVar.get("actNextNodeApprover").toString());

                runtimeService.setVariable(processInstance.getProcessInstanceId(),variableKey,processVar.get("actNextNodeApprover"));
                runtimeService.removeVariable(processInstance.getProcessInstanceId(), "actNextNodeApprover");
            }else if (runtimeService.getVariable(processInstance.getProcessInstanceId(), variableKey) != null){
                approverArray = JSONArray.parseArray(runtimeService.getVariable(processInstance.getProcessInstanceId(), variableKey).toString());
            }

            if (approverArray != null){
                for (int i = 0; i < approverArray.size(); i++) {
                    SysUser user = UserUtils.getUser(approverArray.getString(i));
                    if (user != null){
                        this.addUserToList(resList,user.getUserName());
                    }
                }
            }
        }
    }

    /**
     * 根据项目团队成员获取审批人
     * @param wfActApprover 审批人配置对象
     * @param resList  审批人集合
     * @param processInstance 流程实例
     * @param processVar 流程变量
     */
    public void getApproverByDealTeam(WfActApprover wfActApprover,List<String> resList,ProcessInstance processInstance,Map<String,Object> processVar){
        Map<String, String> dataTableAndDataId = this.getDataTableAndDataId(processInstance, processVar);
        String dataTable = dataTableAndDataId.get("actDataTable");
        String dataId = dataTableAndDataId.get("actDataId");
        String dealId = null;

        String companyId = null;

        if ("wf_bus_node".equals(dataTable)){
            WfBusNode wfBusNode = wfBusNodeService.get(dataId);
            dealId = wfBusNode.getBusId();
        }else {
            Map<String, Object> data = sqlDao.getData(dataTable, dataId);
            if (data.get("deal_id") != null && !"".equals(data.get("deal_id"))){
                dealId = data.get("deal_id").toString();
            }
            if (data.get("company_id") != null && !"".equals(data.get("company_id"))){
                companyId = data.get("company_id").toString();
            }
        }

        // 根据项目查询团队成员
        if (StringUtils.isNotBlank(dealId)){
            List<String> dealTeamList = new ArrayList<>();
            // 查询风控部团队成员
            if(StringUtils.equals(wfActApprover.getApprover(),"X")){
                dealTeamList =  wfActApproverDao.findDealTeamByDealId(StringUtils.symbolHandler(dealId), "风控主办经理");
            }else{
                dealTeamList =  wfActApproverDao.findDealTeamByDealId(StringUtils.symbolHandler(dealId), wfActApprover.getApprover());
            }
            this.addUserToList(resList,dealTeamList);
        }else if(StringUtils.isNotBlank(companyId)){
            List<String> dealTeamList = wfActApproverDao.findDealTeamByCompanyId(companyId, wfActApprover.getApprover());
            this.addUserToList(resList,dealTeamList);
        }

        // 根据公司ID查询相关项目的团队成员

    }

    /**
     * 根据基金团队成员获取审批人
     * @param wfActApprover 审批人配置对象
     * @param resList  审批人集合
     * @param processInstance 流程实例
     * @param processVar 流程变量
     */
    public void getApproverByFundTeam(WfActApprover wfActApprover,List<String> resList,ProcessInstance processInstance,Map<String,Object> processVar){
        Map<String, String> dataTableAndDataId = this.getDataTableAndDataId(processInstance, processVar);
        String dataTable = dataTableAndDataId.get("actDataTable");
        String dataId = dataTableAndDataId.get("actDataId");
        String fundId = null;
        if ("wf_bus_node".equals(dataTable)){
            WfBusNode wfBusNode = wfBusNodeService.get(dataId);
            fundId = wfBusNode.getBusId();

            if (!"fund".equals(wfBusNode.getBusType())){
                String budDataId = wfBusNode.getDataId();
                String budDataTable = ActUtils.getFormTable(wfBusNode.getFormType(),wfBusNode.getFormId());
                Map<String, Object> data = sqlDao.getData(budDataTable, budDataId);
                if (data.get("fund_id") != null && !"".equals(data.get("fund_id"))){
                    fundId = data.get("fund_id").toString();
                }
            }

        }else {
            Map<String, Object> data = sqlDao.getData(dataTable, dataId);
            if (data.get("fund_id") != null && !"".equals(data.get("fund_id"))){
                fundId = data.get("fund_id").toString();
            }
        }

        if (StringUtils.isNotBlank(fundId)){
            List<String> fundTeamList = wfActApproverDao.findUserByFundTeam(fundId, wfActApprover.getApprover());
            if (fundTeamList.size() > 0){
                this.addUserToList(resList,fundTeamList);
            }else {
                this.getFundTeamByDeal(dataTable,dataId,resList,wfActApprover);
            }
        }
    }

    public String getDealId(String dataTable,String dataId){
        String dealId = null;

        if ("wf_bus_node".equals(dataTable)){
            WfBusNode wfBusNode = wfBusNodeService.get(dataId);
            dealId = wfBusNode.getBusId();

            if (!"deal".equals(wfBusNode.getBusType())){
                String budDataId = wfBusNode.getDataId();
                String budDataTable = ActUtils.getFormTable(wfBusNode.getFormType(),wfBusNode.getFormId());
                Map<String, Object> data = sqlDao.getData(budDataTable, budDataId);
                if (data.get("deal_id") != null && !"".equals(data.get("deal_id"))){
                    dealId = data.get("deal").toString();
                }
            }

        }else {
            Map<String, Object> data = sqlDao.getData(dataTable, dataId);
            if (data.get("deal_id") != null && !"".equals(data.get("deal_id"))){
                dealId = data.get("deal_id").toString();
            }

            // OA合同
            if (StringUtils.isBlank(dealId)){
                if (data.get("project_or_fund") != null && !"".equals(data.get("project_or_fund"))){
                    dealId = data.get("project_or_fund").toString();
                }
            }

            // 根据公司ID查询项目ID(只返回第一个)
            if (StringUtils.isBlank(dealId) && data.get("company_id") != null){
                String companyId = data.get("company_id").toString();
                dealId = wfActApproverDao.findDealIdByCompanyId(companyId);

            }
        }

        return dealId;
    }


    /**
     * 根据项目投资主体获取基金团队成员
     * @param dataTable
     * @param dataId
     * @param resList
     */
    public void getFundTeamByDeal(String dataTable,String dataId,List<String> resList,WfActApprover wfActApprover){
        String dealId = this.getDealId(dataTable, dataId);
        List<String> dealInvestmentList = wfActApproverDao.fundDealInvestment(dealId);
        for (String fundId : dealInvestmentList) {
            List<String> fundTeamList = wfActApproverDao.findUserByFundTeam(fundId, wfActApprover.getApprover());
            this.addUserToList(resList,fundTeamList);
        }

    }


    /**
     * 将审批人名称添加到List,去除重复
     * @param resList
     * @param loginName
     */
    public void addUserToList(List<String> resList,String loginName){
        if (!resList.contains(loginName) && UserUtils.checkUserName(loginName)){
            resList.add(loginName);
        }
    }

    /**
     * 将审批人名称添加到List,去除重复
     * @param resList
     * @param loginNameList
     */
    public void addUserToList(List<String> resList,List<String> loginNameList){
        for (String loginName : loginNameList) {
            if (!resList.contains(loginName)){
                SysUser user = UserUtils.getUserByUserName(loginName);
                if (user != null && "1".equals(user.getStatus())){
                    resList.add(loginName);
                }
            }
        }
    }


    /**
     * 将审批人名称添加到List,去除重复
     * @param resList
     * @param userId
     */
    public void addUserIdToList(List<String> resList,String userId){
        SysUser user = UserUtils.getUser(userId);
        if (user!=null && "1".equals(user.getStatus()) && !resList.contains(user.getUserName()) && UserUtils.checkUserName(user.getUserName())){
            resList.add(user.getUserName());
        }
    }

    /**
     * 根据用户配置获取审批人
     * @param wfActApprover
     * @return
     */
    public void getApproverByUser(WfActApprover wfActApprover,List<String> resList){
        SysUser user = UserUtils.getUserByUserName(wfActApprover.getApprover());
        if (user != null && "1".equals(user.getStatus())){
            this.addUserToList(resList,wfActApprover.getApprover());
        }
    }

    /**
     * 根据部门配置获取审批人
     * @param wfActApprover
     * @return
     */
    public void getApproverByDept(WfActApprover wfActApprover,List<String> resList){
        SysDept sysDept = DeptUtils.getByKey(wfActApprover.getApprover());
        if (sysDept != null){
            List<SysUser> userList = UserUtils.getUserListByDeptId(sysDept.getId());
            for (SysUser sysUser : userList) {
                this.addUserToList(resList,sysUser.getUserName());
            }
        }
    }

    /**
     * 根据角色配置获取审批人
     * @param wfActApprover
     * @return
     */
    public void getApproverByRole(WfActApprover wfActApprover,List<String> resList){
        List<String> userIdList = UserUtils.getUserIdByRoleKey(wfActApprover.getApprover());
        for (String userId : userIdList) {
            this.addUserIdToList(resList,userId);
        }
    }

    /**
     * 根据相对角色配置获取审批人
     * @param wfActApprover
     * @param resList
     */
    public void getApproverByRelative(WfActApprover wfActApprover,List<String> resList,ProcessInstance processInstance,Map<String,Object> processVar){
        String actId = null;
        if (processInstance == null && processVar.get("actId") != null){
            actId = processVar.get("actId").toString();
        }else if (processInstance != null){
            actId = processInstance.getId();
        }



        String apply = null;
        if (processVar != null) {
            apply = processVar.get("applyUserName").toString();
        } else {
            apply = ((ExecutionEntity) processInstance).getVariable("applyUserName").toString();
        }
        SysUser applyUser = UserUtils.getUserByUserName(apply);
        //申请人部门
        SysDept applyDept = null;
        if (applyUser != null && StringUtils.isNotBlank(applyUser.getDeptId())){
            applyDept = sysDeptDao.selectDeptById(applyUser.getDeptId());
        }

        //申请人
        if ("apply".equals(wfActApprover.getApprover())){
            HistoricProcessInstance hiProcessInstance = ActProcessUtils.getHiProcessInstance(actId);
            if (hiProcessInstance != null){
                this.addUserToList(resList,hiProcessInstance.getStartUserId());
            } else {
                this.addUserToList(resList,UserUtils.getUserName());
            }

        //申请人部门负责人
        }else if ("applyDeptLeader".equals(wfActApprover.getApprover())){
            String nextApply = ((ExecutionEntity) processInstance).getVariable("nextApply").toString();
            if (StringUtils.isNotBlank(nextApply)) {
                try {
                    JSONArray jsonArray = JSONArray.parseArray(nextApply);
                    if (jsonArray != null && jsonArray.size() > 0) {
                        for (Object o : jsonArray) {
                            JSONObject object = JSONObject.parseObject(o.toString());
                            String user = object.get("user").toString();
                            if (StringUtils.isNotBlank(user)){
                                this.addUserIdToList(resList, user);
                            } else {
                                if (applyDept != null && StringUtils.isNotBlank(applyDept.getLeader())) {
                                    this.addUserIdToList(resList, applyDept.getLeader());
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                    if (applyDept != null && StringUtils.isNotBlank(applyDept.getLeader())) {
                        this.addUserIdToList(resList, applyDept.getLeader());
                    }
                }
            } else {
                if (applyDept != null && StringUtils.isNotBlank(applyDept.getLeader())) {
                    this.addUserIdToList(resList, applyDept.getLeader());
                }
            }

        //申请人部门副总
        }else if ("applyDeptLeadership".equals(wfActApprover.getApprover())){
            if (applyDept != null && StringUtils.isNotBlank(applyDept.getLeadership())){
                this.addUserIdToList(resList,applyDept.getLeadership());
            }
        //申请人部门分管领导
        }else if ("applyDeptDeputyGeneral".equals(wfActApprover.getApprover())){
            if (applyDept != null && StringUtils.isNotBlank(applyDept.getDeputyGeneral())){
                this.addUserIdToList(resList,applyDept.getDeputyGeneral());
            }
        //上一审批人
        }else if ("approver".equals(wfActApprover.getApprover())){
            this.addUserToList(resList,ActUtils.getLastAssignee(actId));
        }
    }

    /**
     * 根据表单属性获取审批人
     * @param wfActApprover
     * @param resList
     */
    public void getApproverByFormField(WfActApprover wfActApprover,List<String> resList,ProcessInstance processInstance,Map<String,Object> processVar){
        Map<String, String> dataTableAndDataId = null;
        if (processVar != null){
            dataTableAndDataId = ActUtils.getDataTableAndDataId(processVar);
        }else {
            dataTableAndDataId = ActUtils.getDataTableAndDataId(((ExecutionEntity) processInstance));
        }

        String deploymentId = null;
        if (processInstance != null){
            deploymentId = processInstance.getDeploymentId();
        }else {
            HistoricProcessInstance historicProcessInstance = ActProcessUtils.getHiProcessInstance(processVar.get("actId").toString());
            deploymentId = historicProcessInstance.getDeploymentId();
        }

        // 解决获取不到deploymentId 的问题
        if (StringUtils.isBlank(deploymentId) && processInstance != null){
            HistoricProcessInstance historicProcessInstance = ActProcessUtils.getHiProcessInstance(processInstance.getProcessInstanceId());
            deploymentId = historicProcessInstance.getDeploymentId();
        }


        String dataTable = dataTableAndDataId.get("actDataTable");
        String dataId = dataTableAndDataId.get("actDataId");

        Map<String, Object> data = sqlDao.getData(dataTable, dataId);

        JSONObject modelMetaInfo = ActModelUtils.getModelMetaInfo(wfActApprover.getModelId(),deploymentId);
        String formType = modelMetaInfo.getString("formType");
        String formId = modelMetaInfo.getString("formId");
        if ("dev".equals(formType)){
            WfApplyFormField wfApplyFormField = wfApplyFormFieldDao.getByApplyFormIdAndFieldName(formId, wfActApprover.getApprover());

            if (wfApplyFormField != null && data.get(wfApplyFormField.getName()) != null){
                String fieldValue = data.get(wfApplyFormField.getName()).toString();

                JSONArray fieldArray = new JSONArray();

                // 判断保存的数据是不是json格式
                if (StringUtils.isNotBlank(fieldValue) && JsonUtils.isJsonArray(fieldValue)){
                    fieldArray = JSONObject.parseArray(fieldValue);
                }else {
                    String[] idArray = data.get(wfApplyFormField.getName()).toString().split(",");
                    for (int i = 0; i < idArray.length; i++) {
                        fieldArray.add(idArray[i]);
                    }
                }

                // 部门类型
                if ("Office".equals(wfApplyFormField.getType())){
                    for (int i = 0; i < fieldArray.size(); i++) {
                        String deptId = fieldArray.getString(i);
                        List<SysUser> userList = UserUtils.getUserListByDeptId(deptId);
                        for (SysUser sysUser : userList) {
                            this.addUserToList(resList,sysUser.getUserName());
                        }
                    }
                // 用户类型
                }else if ("User".equals(wfApplyFormField.getType())){
                    for (int i = 0; i < fieldArray.size(); i++) {
                        String userId = fieldArray.getString(i);
                        SysUser user = UserUtils.getUser(userId);
                        if (user != null){
                            this.addUserToList(resList,user.getUserName());
                        }
                    }
                }



            }

        }


    }

}
